# -*- coding: utf-8 -*-
from flask import json
import redis
from scrapy_redis.spiders import RedisSpider
from scrapy import Request, FormRequest
from spider.ops import Ops

from facility.time_fn import timestamp2string

import subprocess


class HuafengSpider(RedisSpider):
    name = 'huafeng'
    redis_key = 'huafeng:start_urls'
    v8host = 'http://localhost:5000/'

    con = redis.Redis(host='localhost', port=6379, db=0)
    con.lpush(redis_key, v8host)

    def parse(self, response):
        total = 9999
        yield FormRequest(url='https://www.xjhfjr.com/financing/sbtz/index.htm',
                          formdata={"currentPage": "1",
                                    "pageSize": "{}".format(total),
                                    "yearRate": "",
                                    "progress": "",
                                    "status": "",
                                    'orderItem': '',
                                    "productId": "",
                                    },
                          dont_filter=True, callback=self.parse_item)

    def parse_item(self, response):
        q = Ops(response)
        for i in q.get_json()['bidList']:
            idx = i["F02"]
            yield FormRequest(url='https://www.xjhfjr.com/financing/sbtz/bdxqData.htm',
                              formdata={"type": "bdxq",
                                        "id": "{}".format(idx),
                                        "pageSize": "10",
                                        "currentPage": "1"
                                        },
                              dont_filter=True, callback=self.parse_detail_end)

    def parse_detail_end(self, response):
        q = Ops(response)
        data = q.get_json()["bdxqData"]["bdxq"]

        dic = {
            "YCFQ": "本息到期一次付清",
            "MYFX": "每月付息,到期还本",
        }

        name = data["F03"]
        amount = str(data["F05"])
        rate = str(data["F06"] * 100) + "%"
        start = str(timestamp2string(data["F22"]))
        cycle = str(data["F09"])
        way = dic[data["F10"]] if data["F10"] in dic else '每月付息,到期还本'
        res = name + " " + amount + " " + rate + " " + start + " " + cycle + " " + way

        subprocess.call("echo  '{}' >> 华丰.txt".format(res), shell=True)
